/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package forms;

import com.sun.lwuit.Command;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.Border;
import domain.controller.file.RegistroController;
import form.components.RegistroListRenderer;
import domain.model.ICategoria;
import domain.model.IRegistro;
import domain.model.file.Registro;
import java.util.Stack;

/**
 *
 * @author ademar.victorino
 */
public class RegistrosForm extends AbstractForm implements ActionListener {

    private List list = new List();
    private AbstractForm retForm;

    private RegistrosForm() {
    }

    public RegistrosForm(AbstractForm returnForm) {
        super();
        this.retForm = returnForm;
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        list.setListCellRenderer(new RegistroListRenderer());
        list.setFixedSelection(List.FIXED_LEAD);
        list.getStyle().setBorder(Border.createEmpty());
        list.addActionListener(this);
        addComponent(list);

        addCommand(new Command("Voltar") {

            public void actionPerformed(ActionEvent evt) {
                retForm.show();
            }
        });
    }

    void show(ICategoria catSel) {

        setTitle("Resultados: " + catSel.getNome());

        try {
            Stack regs = RegistroController.getInstance().listRegistros(catSel);
            for (int i = 0; i < regs.size(); i++) {
                list.addItem(regs.elementAt(i));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.show();
    }

    public void show(final String word) {

        WaitForm.getInstance().show();
        Thread t = new Thread(new Runnable() {

            public void run() {

                int count = 0;
                try {
                    Stack vec = RegistroController.getInstance().buscarRegistros(word);
                    for (int i = 0; i < vec.size(); i++) {
                        Registro reg = (Registro) vec.elementAt(i);
                        list.addItem(reg);
                        reg = null;
                        count++;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();//showError(this);
                }

                setTitle("Resutados encontrados: " + count);
                WaitForm.getInstance().setVisible(false);
                show();
            }
        });
        t.start();
    }

    public void actionPerformed(ActionEvent arg0) {
        WaitForm.getInstance().show();
        new Thread(new Runnable() {

            public void run() {
                IRegistro reg = (IRegistro) list.getSelectedItem();
                new DetalheRegistroForm().show(reg, RegistrosForm.this);
            }
        }).start();
    }
}
